<template>
  <view class="profile-container">
    <!-- 个人信息头部（保持原有结构） -->
    <view class="profile-header">
      <view class="avatar-wrapper">
        <image 
          class="avatar" 
          :src="userInfo.pic || '/static/avatar/default.png'" 
          mode="widthFix"
          @error="userInfo.pic = '/static/avatar/default.png'"
        ></image>
      </view>
      
      <view class="user-info">
        <!-- 重点修复：星级评分容器 -->
        <view class="name-star">
          <view class="name">{{ userInfo.userName || '未命名用户' }}</view>
          <!-- 星级评分（优化定位和宽度，解决重叠） -->
          <view class="star-group">
            <!-- 星级背景+填充容器（固定宽度，避免被数字挤压） -->
            <view class="star-container">
              <view class="star-bg">★★★★★</view>
              <view class="star-fill" :style="{ width: starWidth }">★★★★★</view>
            </view>
            <!-- 评分数字（与星级并列，而非重叠） -->
            <view class="star-text">{{ userInfo.star.toFixed(1) || '0.0' }}</view>
          </view>
        </view>
        
        <view class="status-wrapper" @click="toggleStatus">
          <view class="status-text" :class="{ online: userInfo.status === 'online' }">
            {{ userInfo.status === 'online' ? '接单中' : '休息中' }}
          </view>
          <switch 
            class="status-switch"
            :checked="userInfo.status === 'online'" 
            @change="toggleStatus"
          ></switch>
        </view>
      </view>
    </view>

    <!-- 用户详细信息 -->
    <view class="user-details-card">
      <view class="detail-item">
        <text class="detail-label">用户ID:</text>
        <text class="detail-value">{{ userInfo.userId || '未设置' }}</text>
      </view>
      <view class="detail-item">
        <text class="detail-label">电话:</text>
        <text class="detail-value">{{ userInfo.phone || '未设置' }}</text>
      </view>
      <view class="detail-item">
        <text class="detail-label">邮箱:</text>
        <text class="detail-value">{{ userInfo.email || '未设置' }}</text>
      </view>
    </view>

    <!-- 以下代码保持不变（数据统计卡片、功能列表等） -->
    <view class="stats-card">
      <view class="stat-item" v-for="(item, index) in statList" :key="index">
        <view class="stat-value" :class="{ money: item.isMoney }">
          {{ item.isMoney ? '¥' : '' }}{{ item.value }}
        </view>
        <view class="stat-label">{{ item.label }}</view>
      </view>
    </view>
    
    <view class="func-list">
      <!-- 功能列表代码保持不变 -->
      <view class="func-item" @click="goToMessages">
        <view class="func-icon-wrapper">
          <text class="func-icon">💬</text>
        </view>
        <text class="func-name">消息通知</text>
        <view class="unread-badge" v-if="userInfo.unreadMsgCount > 0">
          {{ userInfo.unreadMsgCount }}
        </view>
        <text class="func-arrow">→</text>
      </view>
      
      <view class="func-item" @click="goToEvaluation">
        <view class="func-icon-wrapper">
          <text class="func-icon">⭐</text>
        </view>
        <text class="func-name">我的评价</text>
        <text class="func-arrow">→</text>
      </view>
	  
	  <!-- 新增：我的工单 -->
	        <view class="func-item" @click="goToOrders">
	          <view class="func-icon-wrapper">
	            <text class="func-icon">📋</text>
	          </view>
	          <text class="func-name">我的工单</text>
	          <!-- 工单数量提示（可选） -->
	          <view class="unread-badge" v-if="userInfo.pendingOrderCount > 0">
	            {{ userInfo.pendingOrderCount }}
	          </view>
	          <text class="func-arrow">→</text>
	        </view>
	        
	        <!-- 新增：设置 -->
	        <view class="func-item" @click="goToSettings">
	          <view class="func-icon-wrapper">
	            <text class="func-icon">⚙️</text>
	          </view>
	          <text class="func-name">设置</text>
	          <text class="func-arrow">→</text>
	        </view>
      
      <view class="func-divider"></view>
	  
      <view class="func-divider"></view>
      
      <view class="func-item logout-item" @click="logout">
        <view class="func-icon-wrapper logout-icon">
          <text class="func-icon">🚪</text>
        </view>
        <text class="func-name">退出登录</text>
        <text class="func-arrow">→</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getEmployeeRating, getEmployeeInfo,getOrderReview } from '../../api/order.js';
import { getOrderList } from '../../api/order.js';

// 添加 userInfo 对象的定义
const userInfo = ref({
  userId: '',
  pic: '/static/avatar/default.png',
  userName: '未命名用户',
  star: 0,
  status: 'online',
  unreadMsgCount: 0,
  pendingOrderCount: 0,
  phone: '',
  email: ''
});

// 计算星级宽度的计算属性
const starWidth = computed(() => {
  const rating = userInfo.value.star || 0;
  // 确保评分在0-5之间
  const clampedRating = Math.max(0, Math.min(5, rating));
  // 计算百分比宽度
  const percentage = (clampedRating / 5) * 100;
  return `${percentage}%`;
});

const router = useRouter();

// 添加模拟数据
const statList = ref([
  { value: 0, label: '已完成订单', isMoney: false },
  { value: 0, label: '总收入', isMoney: true },
  { value: 0, label: '平均评分', isMoney: false }
]);

// 页面加载时获取用户信息
onMounted(() => {
  // 从本地存储获取用户信息
  const storedUserInfo = uni.getStorageSync('userInfo');
  if (storedUserInfo) {
    userInfo.value = { ...userInfo.value, ...storedUserInfo };
    
    // 获取用户平均星级评分
    fetchUserRating(storedUserInfo.userId);
    
    // 获取用户详细信息
    fetchUserInfo(storedUserInfo.userId);
	
	// 获取订单统计数据
	fetchOrderStatistics(storedUserInfo.userId);
  }
});

// 获取订单统计数据（已完成订单数量、总收入和平均评分）
const fetchOrderStatistics = async (userId) => {
  try {
    const res = await getOrderList();
    if (res && res.code === 0) {
      // 获取当前登录员工ID
        const userInfo = uni.getStorageSync('userInfo');
        const employeeId = userInfo?.userId;
        
        // 按创建时间降序排序
        let sortedOrders = (res.data || []).sort((a, b) => {
          // 如果有createTime字段，按createTime排序
          if (a.createTime && b.createTime) {
            return new Date(b.createTime) - new Date(a.createTime);
          }
          // 如果没有createTime字段，按id降序排序
          return b.id - a.id;
        });
        
        // 如果有员工ID，则只显示分配给该员工的订单
        if (employeeId) {
          sortedOrders = sortedOrders.filter(order => {
            // 检查订单是否有employeeId字段并且与当前员工ID匹配
            // 注意：使用 == 而不是 === 因为ID可能是字符串或数字类型
            return order.employeeId == employeeId;
          });
        }
        
        // 筛选出已完成的订单（已支付且状态为2(已完成)或4(已评论)的订单）
      const completedOrders = sortedOrders.filter(order =>
        order.payStatus === 1 && (order.status === 2 || order.status === 4)
      );
	  // 计算已完成订单数量
	  const completedCount = completedOrders.length;
      
      // 计算总收入 (servicePay字段的总和)
      const totalIncome = completedOrders.reduce((sum, order) => {
        return sum + (parseFloat(order.servicePay) || 0);
      }, 0);
	  // 计算平均评分
	   let totalRating = 0;
	   let ratedOrderCount = 0;
	   
	   // 遍历已完成的订单，获取评分
	   for (const order of completedOrders) {
	     // 只有状态为4（已评论）的订单才有可能有评分
	     if (order.status === 4) {
	       try {
	         const reviewRes = await getOrderReview(order.id);
	         if (reviewRes && reviewRes.code === 0 && reviewRes.data) {
	           const rating = reviewRes.data.starRating || reviewRes.data.rating || reviewRes.data.stars || 0;
	           if (rating > 0) {
	             totalRating += rating;
	             ratedOrderCount++;
	           }
	         }
	       } catch (error) {
	         console.error(`获取订单 ${order.id} 的评价失败:`, error);
	       }
	     }
	   }
	   
	   // 计算平均评分
	   const averageRating = ratedOrderCount > 0 ? (totalRating / ratedOrderCount).toFixed(1) : 0;
      // 更新统计数据
       statList.value[0].value = completedCount; // 已完成订单数量
       statList.value[1].value = totalIncome.toFixed(2); // 总收入
	   statList.value[2].value = averageRating; // 平均评分
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
  }
};
// 获取用户平均星级评分
const fetchUserRating = async (userId) => {
  try {
    const res = await getEmployeeRating(userId);
    console.log('获取到的用户星级评分:', res); // 添加日志查看返回数据
    if (res && res.code === 0) {
      // 更新用户星级评分
      // 修复：直接使用 res.data 而不是 res.data.totalRating
      userInfo.value.star = res.data || 0;
      console.log('更新后的星级评分:', userInfo.value.star); // 添加日志查看更新后的值
    } else {
      console.error('获取用户星级评分失败:', res?.msg || '未知错误');
    }
  } catch (error) {
    console.error('获取用户星级评分异常:', error);
  }
};

// 获取用户详细信息
const fetchUserInfo = async (userId) => {
  try {
    const res = await getEmployeeInfo(userId);
    console.log('获取到的用户详细信息:', res); // 添加日志查看返回数据
    if (res && res.code === 0) {
      // 更新用户详细信息
      const employeeInfo = res.data || {};
      userInfo.value.userId = userId;
      userInfo.value.userName = employeeInfo.userName || userInfo.value.userName;
      userInfo.value.pic = employeeInfo.pic || userInfo.value.pic;
      userInfo.value.phone = employeeInfo.phone || '';
      userInfo.value.email = employeeInfo.email || '';
      console.log('更新后的用户信息:', userInfo.value); // 添加日志查看更新后的值
    } else {
      userInfo.value.userId = userId;
      console.error('获取用户详细信息失败:', res?.msg || '未知错误');
    }
  } catch (error) {
    userInfo.value.userId = userId;
    console.error('获取用户详细信息异常:', error);
  }
};

// 定义方法
const toggleStatus = () => {
  console.log('切换状态');
};

const goToMessages = () => {
  console.log('跳转到消息通知页面');
};

const goToEvaluation = () => {
  console.log('跳转到我的评价页面');
};

const goToOrders = () => {
  console.log('跳转到我的工单页面');
};

const goToSettings = () => {
  console.log('跳转到设置页面');
};

const logout = () => {
  console.log('退出登录');
  // 清除本地存储的用户信息
  uni.removeStorageSync('userInfo');
  // 跳转到登录页面
  try {
    // 使用Vue Router跳转
    if (router && typeof router.push === 'function') {
      console.log('使用Vue Router跳转到登录页面');
      router.push('/pages/login/login');
    } else {
      // 降级处理 - 使用uni-app原生跳转
      console.log('使用uni-app原生跳转到登录页面');
      uni.redirectTo({ url: '/pages/login/login' });
    }
  } catch (e) {
    console.error('路由跳转异常:', e);
    // 最后的兜底方案
    try {
      uni.redirectTo({ url: '/pages/login/login' });
    } catch (redirectError) {
      console.error('redirectTo也失败了:', redirectError);
      // 如果redirectTo也失败，尝试switchTab（虽然不太可能适用于登录页面）
      try {
        uni.switchTab({ url: '/pages/login/login' });
      } catch (switchTabError) {
        console.error('switchTab也失败了:', switchTabError);
        uni.showToast({ title: '页面跳转失败', icon: 'none' });
      }
    }
  }
};

</script>

<style scoped>
/* 此处省略样式代码（保持原有样式不变） */
.profile-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20rpx;
}

.profile-header {
  padding: 60rpx 30rpx 40rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 0 0 30rpx 30rpx;
  color: #fff;
  text-align: center;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
}

.avatar-wrapper {
  width: 160rpx;
  height: 160rpx;
  margin: 0 auto 30rpx;
  border-radius: 50%;
  border: 6rpx solid rgba(255, 255, 255, 0.3);
  padding: 4rpx;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.name-star {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20rpx;
  gap: 15rpx;
}

.name {
  font-size: 36rpx;
  font-weight: 600;
}

.star-container {
  position: relative;
  color: #ffd700;
  font-size: 24rpx;
  display: flex;
  align-items: center;
}

.star-bg {
  color: rgba(255, 255, 255, 0.3);
}

.star-fill {
  position: absolute;
  left: 0;
  top: 0;
  overflow: hidden;
  color: #ffd700;
}

.star-text {
  margin-left: 8rpx;
  color: #fff;
}

.status-wrapper {
  display: inline-flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 8rpx 20rpx;
  border-radius: 30rpx;
  gap: 15rpx;
}

.status-text {
  font-size: 24rpx;
  color: #fff;
}

.status-text.online {
  color: #a8ff78;
}

/* 用户详细信息卡片样式 */
.user-details-card {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  margin: 20rpx;
  padding: 30rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
}

.detail-item {
  display: flex;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-label {
  width: 100rpx;
  font-size: 28rpx;
  color: #666;
}

.detail-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.location-info {
  padding: 0;
  background-color: #fff;
  margin: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.location-header {
  padding: 20rpx 30rpx 10rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.location-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.location-content {
  padding: 20rpx 30rpx;
}

.location-text {
  font-size: 28rpx;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
  min-height: 40rpx;
}

.get-location-btn {
  background-color: #1677ff;
  color: white;
  border: none;
  padding: 15rpx 20rpx;
  border-radius: 10rpx;
  font-size: 26rpx;
  cursor: pointer;
  width: 100%;
}

.get-location-btn::after {
  border: none;
}

.get-location-btn:active {
  background-color: #0e62d4;
}

.stats-card {
  display: flex;
  justify-content: space-around;
  padding: 30rpx 20rpx;
  margin: 20rpx;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-value {
  font-size: 32rpx;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 10rpx;
}

.stat-value.money {
  color: #1677ff;
}

.stat-label {
  font-size: 22rpx;
  color: #6b7280;
}

.func-list {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  margin: 0 20rpx 30rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
}

.func-item {
  display: flex;
  align-items: center;
  padding: 25rpx 30rpx;
  font-size: 28rpx;
  color: #1f2937;
}

.func-icon-wrapper {
  width: 60rpx;
  height: 60rpx;
  border-radius: 15rpx;
  background-color: #f0f9ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 25rpx;
}

.func-icon {
  font-size: 32rpx;
  color: #1677ff;
}

.func-name {
  flex: 1;
}

.func-arrow {
  color: #d1d5db;
  font-size: 30rpx;
}

.unread-badge {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  font-size: 22rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15rpx;
}

.func-divider {
  height: 1rpx;
  background-color: #f3f4f6;
  margin: 0 30rpx;
}

.logout-item {
  color: #ff4d4f;
}

.logout-icon {
  background-color: #fff2f0;
}

.logout-icon .func-icon {
  color: #ff4d4f;
}
</style>